﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZXing;
using ZXing.Common;

namespace RSALicCore
{
    /// <summary>
    /// 二维码辅助类
    /// </summary>
    public class QRCodeHelper
    {
        /// <summary>
        /// 创建二维码图片
        /// </summary>
        /// <param name="data"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        public static Bitmap Create(string data, int size = 256)
        {
            if (string.IsNullOrEmpty(data))
            {
                return null;
            }

            var byteMatrix = new MultiFormatWriter().encode(data, BarcodeFormat.QR_CODE, size, size);

            string Scolor = "0xFF000000";//二维码颜色
            string Qcolor = "0xFFFFFFFF";//背景颜色
            return toBitmap(byteMatrix, Scolor, Qcolor);
        }

        /// <summary>
        /// 解析二维码
        /// 解析性能排序：
        /// QRCodeDecoder > MultiFormatReader
        /// </summary>
        /// <param name="bmp"></param>
        /// <returns></returns>
        public static string Parse(Image bmp)
        {
            var reader = new BarcodeReader();
            reader.Options.CharacterSet = "UTF-8";
            using (var tbmp = new Bitmap(bmp))
            {
                var rr = reader.Decode(tbmp);
                return rr?.Text;
            }
        }

        public static Result[] ParseAll(Image bmp)
        {
            var reader = new BarcodeReader();
            reader.Options.CharacterSet = "UTF-8";
            using (var tbmp = new Bitmap(bmp))
            {
                return reader.DecodeMultiple(tbmp);
            }
        }

        static Bitmap toBitmap(BitMatrix matrix, string scolor, string qcolor)
        {
            int width = matrix.Width;
            int height = matrix.Height;
            Bitmap bmap = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            for (int x = 0; x < width; x++)
            {
                for (int y = 0; y < height; y++)
                {
                    bmap.SetPixel(x, y, matrix[x,y] ? ColorTranslator.FromHtml(scolor) : ColorTranslator.FromHtml(qcolor));
                }
            }

            return bmap;
        }
    }
}
